package learn.Thread;

import java.util.concurrent.CountDownLatch;

public class LearnCountDownLatch {
    public static void main(String[] args) throws InterruptedException {
        //继承Thread方式来创建线程
        CountDownLatch latch = new CountDownLatch(3);//局部
        CountDownLatch latch2 = new CountDownLatch(3);//全局
        System.out.println("程序开始");
        new copyText(latch,latch2).start();
        new copyText(latch,latch2).start();
        new copyText(latch,latch2).start();
        latch2.await();
        System.out.println("程序结束");
    }
}

class copyText extends Thread{
    private CountDownLatch latch;
    private CountDownLatch latch2;
    public copyText(CountDownLatch latch,CountDownLatch latch2){
        this.latch = latch;
        this.latch2 = latch2;
    }
    @Override
    public void run() {
        for (int i = 0; i < 6; i++) {
            System.out.println("处理批次："+i+"，子线程正在执行:"+Thread.currentThread().getName());
            try {
                sleep(1000);
                latch.countDown(); //表示任务完成，等待其他线程。
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        latch2.countDown();
    }
}



